package com.coco.thread.join;

/**
 * 线程排队执行
 * join 加入让出线程
 * 在线程A中执行 B.join() 表示线程A让出时间让B先执行，等B执行完成，A再继续执行。
 */
public class ThreadJoin {

    public static class ThreadA extends Thread{
        private Thread joinThread;//要插队的线程。
        public ThreadA(){

        }
        public ThreadA(Thread joinThread){
            this.joinThread =joinThread;
        }
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName()+" 排队打饭");
            try {
                if(joinThread!=null){//要插队的线程存在，则让出时间，让插队的先执行。
                    joinThread.join();
                }
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+" 打饭打饭完成");
        }
    }
    public static class ThreadB extends Thread{
        private Thread joinThread;//要插队的线程。
        public ThreadB(){

        }
        public ThreadB(Thread joinThread){
            this.joinThread =joinThread;
        }
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName()+" 排队打饭");
            try {
                if(joinThread!=null){//要插队的线程存在，则让出时间，让插队的先执行。
                    joinThread.join();
                }
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+" 打饭打饭完成");
        }
      }

    public static class ThreadC extends Thread {
        private Thread joinThread;//要插队的线程。
        public ThreadC() {
        }
        public ThreadC(Thread joinThread) {
            this.joinThread = joinThread;
        }
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + " 排队打饭");
            try {
                if (joinThread != null) {//要插队的线程存在，则让出时间，让插队的先执行。
                    joinThread.join();
                }
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " 打饭打饭完成");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ThreadA a = new ThreadA();
        a.setName("老A");
        a.start();

        ThreadB b = new ThreadB(a);//礼让A
//        ThreadB b = new ThreadB();//不让
        b.setName("老B");
        b.start();

        ThreadC c = new ThreadC(b);//礼让B
//        ThreadC c = new ThreadC();//不让
        c.setName("老C");
        c.start();


    }

}
